package com.test.com.bluetoothchatandroid.thread;

import android.bluetooth.BluetoothSocket;

import com.orhanobut.logger.Logger;
import com.test.com.bluetoothchatandroid.global.ChatConstant;
import com.test.com.bluetoothchatandroid.utils.BluetoothChatHelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ${cs} on 2018/4/20.
 * @author saviorT
 * 连接后用于维护的线程
 */

public class ConnectedThread extends Thread {

	private final BluetoothChatHelper mHelper;
	private final BluetoothSocket mSocket;
	private final OutputStream mOutputStream;
	private final InputStream mInputStream;



	public ConnectedThread(BluetoothChatHelper bluetoothChatHelper,
	                       BluetoothSocket socket,String socketType) {
		Logger.d("create ConnectedThread: " + socketType);
		this.mHelper = bluetoothChatHelper;
		this.mSocket = socket;
		InputStream inputStream= null;
		OutputStream outputStream = null;

		try{
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
		}catch (IOException e){
			Logger.d("初始化IO异常",e.getStackTrace());
		}

		mInputStream = inputStream;
		mOutputStream = outputStream;

	}

	@Override
	public void run() {
		Logger.d("Begin ConnectedThread");
		int bytes;
		byte[] buffer = new byte[1024];
		// keep listening to the InputStream while connected
		while (true){
			try{
				bytes = mInputStream.read(buffer);
				byte[] data = new byte[bytes];
				System.arraycopy(buffer,0,data,0,data.length);
				mHelper.getHandler().obtainMessage(ChatConstant.MESSAGE_READ,bytes,-1,data).sendToTarget();
			}catch (IOException e){
				Logger.d("读流操作IO异常,未能开启接收消息线程",e.getStackTrace());
				mHelper.start(false);
				break;
			}
		}
	}


	public void write(byte[] buffer){
		if (mSocket.isConnected()){
			try {
				mOutputStream.write(buffer);
				mHelper.getHandler().obtainMessage(ChatConstant.MESSAGE_WRITE,-1,-1,buffer).sendToTarget();
			}catch (IOException e){
				Logger.d("写流操作IO异常",e.getStackTrace());
			}
		}
	}

	public void cancel(){
		try {
			mSocket.close();
		} catch (IOException e) {
			Logger.d("接收消息Socket关闭失败",e.getStackTrace());
		}
	}

}
